<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入员工姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
<!--      <el-form-item label="员工编码" prop="userNo">
        <el-input v-model="queryParams.userNo" placeholder="请输入员工编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>-->
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['pekingfish:app-user:create']"
        >新增
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" border :data="list">
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['pekingfish:app-user:update']"
          >修改
          </el-button>
          <el-button @click="editStatus(scope.row,1)" type="text" size="small"
                     v-show="scope.row.enabled === undefined || scope.row.enabled === 0 ">
            禁用
          </el-button>
          <el-button @click="editStatus(scope.row,0)"  type="text" size="small"
                     v-show="scope.row.enabled === 1 ">
            启用
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="自增主键" v-if="false" align="center" prop="id"/>
      <el-table-column label="姓名" align="center" prop="userName"/>
<!--      <el-table-column label="头像" align="center" prop="headImg" min-width="150px">
        <template v-slot="scope">
          <image-preview :src="scope.row.headImg" :width="'100px'"></image-preview>
        </template>
      </el-table-column>-->
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="仓库权限" align="center" prop="warehouseName">
<!--        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.app_user_type" :value="scope.row.userType"/>
        </template>-->
      </el-table-column>
      <el-table-column label="移动端权限" align="center" prop="mobileConfigNames">
<!--      <template v-slot="scope">
        <dict-tag :type="DICT_TYPE.app_account_type" :value="scope.row.accountType"/>
      </template>-->
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="enabled">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.enabled"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="600px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入员工姓名"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码"/>
        </el-form-item>

        <el-form-item label="仓库权限" prop="warehouseCode">
<!--          <select-table mode="dialog" v-model="selectTableVal" :fetchFun="fetchFun" :columns="columns" :props="props" :multiple="true"
                        :query="query" @change="handleChange" :pagination="false">
          </select-table>-->
          <el-select v-model="form.warehouseCode" placeholder="请选择仓库" clearable size="small" multiple style="width: 100%">
            <el-option v-for="dict in warehouseDatas"
                       :key="dict.code" :label="dict.name" :value="dict.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="移动端权限" prop="mobileConfig">
          <el-checkbox-group v-model="mobileConfig">
            <el-checkbox v-for="item in mobileConfigList" :key="item.value" :label="item.value">{{item.label}}</el-checkbox>
          </el-checkbox-group>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createAppUser,
  updateAppUser,
  deleteAppUser,
  userDetail,
  getAppUserPage,
  exportAppUserExcel
} from '@/api/pekingfish/appUser'
import {DICT_TYPE, getDictDatas} from "@/utils/dict"
import ImageUpload from '@/components/ImageUpload'
import ImagePreview from '@/components/ImagePreview'
import { getBusinessList } from '@/api/merchantManagement/business'
import { getBranchCompanyByTenantId } from '@/api/merchantManagement/branchCompany'
import { getStoreBySuTenantId } from '@/api/merchantManagement/store'
import {getWarehouseList} from "@/api/pekingfish/warehouse";
import SelectTable from '@/components/select-table/index.vue'

export default {
  model: {
    prop: "value",
    event: "inputFun"
  },
  name: 'AppSaleUser',
  components: {
    ImageUpload, ImagePreview, SelectTable
  },
  data() {
    return {
      mobileConfigList:getDictDatas(DICT_TYPE.sale_warehouse_type),
      mobileConfig:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户管理列表
      list: [],
      // 商户名称
      tenants: [],
      // 分公司名称
      subTenants: [],
      //门店名称
      shops: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        userName: null,
        userNo: null,
        phone: null,
        userType: null,
        accountType: null,
        mobileConfig: null,
        entrepotConfig: null,
        createTime: [],
        collectFlag: null,
        enabled: null,
        subTenantId: null,
        shopId: null,
        email: null,
        address: null,
        ratio: null,
        headImg: null,
        warehouseCode: null,
        warehouseName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
        userNo: [{ required: true, message: '员工编码不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }],
        warehouseCode: [{ required: true, message: '仓库权限不能为空', trigger: 'blur' }],
        mobileConfig: [{ required: true, message: '移动端权限不能为空', trigger: 'blur' }],
        enabled: [{ required: true, message: '禁用标识', trigger: 'blur' }],
        ratio: [{ required: true, message: '渠道商报价折算比例不能为空', trigger: 'blur' }]
      },
      // --下拉表格----
      selectTableVal: null,
      columns: [
        {prop: 'code', label: '仓库编码'},
        {prop: 'name', label: '仓库名称'}
      ],
      props: {
        label: 'name',
        value: 'code',
      },
      query: [{prop: 'code', label: '仓库编码'}, {prop: 'name', label: '仓库名称'}],
      fetchFun: getWarehouseList,
      warehouseDatas:[],
      tableData: [],
    }
  },
  created() {
    this.getList()
    // 商户名称
    getBusinessList().then(response => {
      this.tenants = response.data.list
    });

    getWarehouseList().then(response => {
      this.warehouseDatas = response.data
    })
  },
  methods: {
    async getTableData() {
      this.loading = true;
      const { data } = await getQuestionTableList(this.queryParams);
      this.loading = false;
      this.total = data.total;
      this.tableData = data.list;
    },
    handleChange(val) {
      console.log("val:", val)
      this.form.warehouseCode = val.map(row => row.code).join(', ');
      this.form.warehouseName = val.map(row => row.name).join(', ');
    },

    /** 查询列表 */
    getList() {
      this.loading = true
      this.queryParams.userType = 3001;
      console.log("this.queryParams:", this.queryParams)
      // 执行查询
      getAppUserPage(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    chooseTenant(tenantId) {
      console.log(tenantId + '获取的id')
      // 分公司名称
      getBranchCompanyByTenantId(tenantId).then(response => {
        this.subTenants = response.data
      })
    },

    chooseSubTenant(subTenantId) {
      console.log(subTenantId + '获取的id')
      // 门店名称
      getStoreBySuTenantId(subTenantId).then(response => {
        this.shops = response.data
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        userName: undefined,
        userNo: undefined,
        phone: undefined,
        userType: undefined,
        accountType: undefined,
        mobileConfig: undefined,
        entrepotConfig: undefined,
        collectFlag: undefined,
        enabled: undefined,
        subTenantId: undefined,
        shopId: undefined,
        email: undefined,
        address: undefined,
        ratio: undefined,
        headImg: undefined,
        warehouseCode: undefined,
        warehouseName: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户管理'
      this.mobileConfig=[]
      this.selectTableVal = null

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      userDetail(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改用户管理'
        //this.selectTableVal = [{id: this.form.userNo, userName: this.form.userName},{id: this.form.userNo, userName: this.form.userName}]
        this.form.warehouseCode = this.form.warehouseCode?this.form.warehouseCode.split(','):[]
        this.mobileConfig=this.form.mobileConfig?this.form.mobileConfig.split(','):[]
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.mobileConfig=this.mobileConfig?this.mobileConfig.join(','):''
      console.log("this.form:",this.form)
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        let warehouseCode = this.form.warehouseCode;
        this.form.warehouseCode=this.form.warehouseCode?this.form.warehouseCode.join(','):''
        let warehouseName= []
        this.warehouseDatas.map(i=>{
          warehouseCode.map(w=>{
            if (i.code == w){
              warehouseName.push(i.name);
            }
          })
        })
        this.form.warehouseName=warehouseName?warehouseName.join(','):''

        this.form.userType = 3001
        // 修改的提交
        if (this.form.id != null) {
          updateAppUser(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
          return
        }
        // 添加的提交
        createAppUser(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除用户管理编号为"' + id + '"的数据项?').then(function() {
        return deleteAppUser(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有用户管理数据项?').then(() => {
        this.exportLoading = true
        return exportAppUserExcel(params)
      }).then(response => {
        this.$download.excel(response, '用户管理.xls')
        this.exportLoading = false
      }).catch(() => {
      })
    },
    editStatus(row,enabled) {
      console.log("enabled:", enabled)
      this.form = row;
      this.form.enabled = enabled;
      console.log("this.form:", this.form)
      updateAppUser(this.form).then(response => {
        this.$modal.msgSuccess("成功");
        this.open = false;
        this.getList();
      });
      return;
    },
  }
}
</script>
